<script setup lang="ts">
import { promptList } from '~/logic'

const selectValue = ref('')
const selectTextLinks = ref<any[]>([])

// 监听是否停止的按钮
let stopTime: any
function watchDomeStop(idClass: string) {
  stopTime && clearInterval(stopTime)
  stopTime = setInterval(() => {
    const element = document.querySelector(idClass)
    if (!element) {
      stopTime && clearInterval(stopTime) // 停止轮询
      // 执行链式内容
      inputTextValue(selectTextLinks.value.shift()).then(() => {
        // 点击确定按钮
        confirm()
      })
    }
  }, 500)
}

// 执行数据回填
function inputTextValue(text: string) {
  const textarea = document?.querySelector('.ql-editor.textarea p')
  const value = textarea!.innerHTML || '' // 输入框中的值
  return new Promise((resolve) => {
    nextTick(() => {
      // 这里会根据prompt结构进行处理, 清空的时候
      textarea!.innerHTML = text?.split(/>>>.*?<<</g).join(`${value}`) || ''
      // 延迟执行focus方法
      setTimeout(() => {
        resolve(true)
      }, 1000)
    })
  })
}

// 这里整理了输入值的问题
function selectPrompt(item: any) {
  selectValue.value = item.id
  // 这里整理一下数据，对已经选择的数据
  selectTextLinks.value = item.prompt.split('&')
  inputTextValue(selectTextLinks.value?.shift())
}

function clear() {
  selectValue.value = ''
  selectTextLinks.value = []
  stopTime && clearInterval(stopTime)
  const textarea = document?.querySelector('.ql-editor.textarea p')
  nextTick(() => {
    textarea!.innerHTML = ''
  })
}

// 一定要点击按钮
function confirm() {
  const inputElement = document.querySelector('.send-button mat-icon.google-symbols')
  inputElement!.click()
  // 兼容链式调用的方法
  if (!selectTextLinks.value.length)
    return
  setTimeout(() => {
    watchDomeStop('.blue-circle svg')
  }, 2000)
}
</script>

<template>
  <ResizableDraggable :left="500" :top="100">
    <template #header>
      Prompt
    </template>
    <div
      class="select-main"
    >
      <div class="prompt-list">
        <template v-for="item in promptList" :key="item.id">
          <div
            v-if="item.status"
            class="prompt-btn"
            :class="[selectValue === item.id ? 'active' : '']"
            @click="selectPrompt(item)"
          >
            {{ item.name }}
          </div>
        </template>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="confirm">
        确定
      </el-button>
      <el-button type="danger" @click="clear">
        清空
      </el-button>
    </template>
  </ResizableDraggable>
</template>

<style scoped>
.prompt-list {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.prompt-btn {
  font-size: 12px;
  box-sizing: border-box;
  padding: 6px 12px;
  margin: 6px;
  border-radius: 6px;
  line-height: 16px;
  text-align: center;
  background: #ffffff;
  cursor: pointer;
  color: #000;
  border: 1px solid #cfcfcf;
  white-space: break-spaces;
}
.prompt-btn.active {
  background: var(--el-color-primary);
  color: #fff;
}
</style>
